/*
 * =====================================================================================
 *
 *       Filename:  1674.c
 *
 *    Description:  the minimum swap num to construct a ordered permutation
 *
 *        Version:  1.0
 *        Created:  2012年06月28日 13时57分15秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Regan (), lcqhigh@gmail.com
 *        Company:
 *
 * =====================================================================================
 */
#include	<stdio.h>
#include <search.h>



//ans += {sizeof cycle - 1}
//but how to judge the cycles
//
int seq[10240];

inline void swap(int *a, int *b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

int count_swap_times(int n)
{
    int swapcount = 0, answer = 0;
    int i = 0, t = 0;
    for (i = 0; i < n; ++i)
    {
        swapcount = 0;
        while (seq[i] != i+1)
        {
            t = seq[i] - 1;
            swap(&seq[t], &seq[i]);
            ++swapcount;
        }
        answer += swapcount;
    }
    return answer;
}

int main(int argc, char *argv[])
{
    int times, count;
    int n, idx;
    scanf("%d", &times);
    while (times--) {
        scanf("%d", &n);
        for (idx = 0; idx < n; ++idx)
        {
            scanf("%d", &seq[idx]);
        }

        count = count_swap_times(n);
        printf ( "%d\n", count);
    }
    return 0;
}
